package com.nineclock.document.service.impl;
import java.util.Date;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nineclock.common.entity.PageResult;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.filter.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.document.dto.*;
import com.nineclock.document.enums.DocumentPermissionEnum;
import com.nineclock.document.mapper.DocCollaborationsMapper;
import com.nineclock.document.mapper.DocFileHistoryMapper;
import com.nineclock.document.mapper.DocFileMapper;
import com.nineclock.document.mapper.DocFolderMapper;
import com.nineclock.document.pojo.DocCollaborations;
import com.nineclock.document.pojo.DocFile;
import com.nineclock.document.pojo.DocFileHistory;
import com.nineclock.document.pojo.DocFolder;
import com.nineclock.document.service.DocCollaborationsService;
import com.nineclock.document.service.DocFileService;
import com.nineclock.system.dto.SysCompanyUserDTO;
import com.nineclock.system.feign.SysCompanyUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Transactional
public class DocFileServiceImpl implements DocFileService {

    @Autowired(required = false)
    private DocFolderMapper folderMapper;

    @Autowired(required = false)
    private DocFileMapper fileMapper;

    @Autowired(required = false)
    private DocFileHistoryMapper historyMapper;

    @Autowired(required = false)
    private DocFileService fileService;

    @Autowired(required = false)
    private SysCompanyUserFeign companyUserFeign;

    @Autowired(required = false)
    private DocCollaborationsMapper collaborationsMapper;

    @Autowired(required = false)
    private DocCollaborationsService collaborationsService;

    @Override
    public DocumentDto queryFolderAndFile(Long parentFoldId) {

        // 查询符合条件的文件夹列表
        List<DocFolderDto> folders = queryFolders(parentFoldId);

        // 查询符合条件的文件列表
        List<DocFileDto> files = queryFiles(parentFoldId);

        // 封装数据
        DocumentDto documentDto = new DocumentDto();
        documentDto.setFiles(files);
        documentDto.setFolders(folders);

        return documentDto;
    }


    /**
     * 查询符合条件的文件列表
     * @param parentFoldId
     * @return
     */
    private List<DocFileDto> queryFiles(Long parentFoldId) {

        List<DocFile> fileList = new ArrayList<>();

        // 1.当前目录下，公共读/公共读写 的文件
        LambdaQueryWrapper<DocFile> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper1.eq(DocFile::getFolderId, parentFoldId);
        wrapper1.eq(DocFile::getStatus, 1);
        wrapper1.in(DocFile::getPermission, DocumentPermissionEnum.ALL_READ.getPermission(),
                DocumentPermissionEnum.ALL_READ_WRITE.getPermission());

        List<DocFile> fileList1 = fileMapper.selectList(wrapper1);
        if (!CollectionUtils.isEmpty(fileList1)) {
            fileList.addAll(fileList1);
        }

        // B.当前目录下，当前用户私有的文件
        LambdaQueryWrapper<DocFile> wrapper2 = new LambdaQueryWrapper<>();
        wrapper2.eq(DocFile::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper2.eq(DocFile::getFolderId, parentFoldId);
        wrapper2.eq(DocFile::getStatus, 1);
        wrapper2.eq(DocFile::getPermission, DocumentPermissionEnum.PRIVATE_READ_WRITE.getPermission());
        // 创建人id等于当前登录用户的员工id
        wrapper2.eq(DocFile::getCreateUserId, CurrentUserHolder.get().getCompanyUserId());

        List<DocFile> fileList2 = fileMapper.selectList(wrapper2);
        if (!CollectionUtils.isEmpty(fileList2)) {
            fileList.addAll(fileList2);
        }


        // C.当前目录下，当前用户是协作者的文件
        List<DocFile> fileList3 = fileMapper.selectFileListByCollaboration(CurrentUserHolder.get().getCompanyId(),
                parentFoldId, CurrentUserHolder.get().getCompanyUserId());

        if (!CollectionUtils.isEmpty(fileList3)) {
            fileList.addAll(fileList3);
        }

        // 文件去重，例如某些文件既是公共读，当前用户又是协作者
        HashSet<DocFile> fileHashSet = new HashSet<>(fileList);

        // 数据转换
        Set<DocFileDto> docFileDtos = BeanHelper.copyWithCollection(fileHashSet, DocFileDto.class);

        List<DocFileDto> docFileDtoList = docFileDtos.stream().map(docFileDto -> {

            // 调用系统微服务Feign接口根据更新人员工id，查询更新人员工信息
            SysCompanyUserDTO updateUserDTO = companyUserFeign.queryCompanyUserById(docFileDto.getUpdateUserId()).getData();
            if (updateUserDTO != null) {
                docFileDto.setUpdateUserName(updateUserDTO.getUserName());
            }

            // 调用系统微服务Feign接口根据创建人员工id，查询创建人员工信息
            SysCompanyUserDTO createUserDTO = companyUserFeign.queryCompanyUserById(docFileDto.getCreateUserId()).getData();
            if (createUserDTO != null) {
                docFileDto.setUserName(createUserDTO.getUserName());
            }

            return docFileDto;

        }).collect(Collectors.toList());

        return docFileDtoList;

    }

    /**
     * 查询符合条件的文件夹列表
     * @return
     */
    private List<DocFolderDto> queryFolders(Long parentFoldId) {
        LambdaQueryWrapper<DocFolder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFolder::getCompanyId, CurrentUserHolder.get().getCompanyId());
        wrapper.eq(DocFolder::getParentId, parentFoldId);
        wrapper.eq(DocFolder::getStatus, 1);

        List<DocFolder> docFolders = folderMapper.selectList(wrapper);

        if (!CollectionUtils.isEmpty(docFolders)) {
            return BeanHelper.copyWithCollection(docFolders, DocFolderDto.class);
        }
        return null;
    }

    @Override
    public DocFileDto getFileByFileId(Long id) {
        DocFile docFile = fileMapper.selectById(id);
        return BeanHelper.copyProperties(docFile, DocFileDto.class);
    }

    @Override
    public List<DocUserCollaborationDTO> queryUsers(Long id) {

        // 调用系统微服务查询当前企业员工列表
        List<SysCompanyUserDTO> companyUserDTOS = companyUserFeign.queryAllCompanyUser().getData();

        // 根据文件id查询文件
        DocFile docFile = fileMapper.selectById(id);

        // 根据文件id查询协作者id集合
        LambdaQueryWrapper<DocCollaborations> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocCollaborations::getFileId, id);
        List<DocCollaborations> collaborationsList = collaborationsMapper.selectList(wrapper);

        // 获取协作者id集合
        List<Long> companyUserIdList = collaborationsList.stream().map(docCollaborations -> {
            return docCollaborations.getCollaborationId();
        }).collect(Collectors.toList());


        // 数据转换，将员工DTO转为DocUserCollaborationDTO
        List<DocUserCollaborationDTO> docUserCollaborationDTOS = companyUserDTOS.stream().map(sysCompanyUserDTO -> {

            DocUserCollaborationDTO docUserCollaborationDTO = new DocUserCollaborationDTO();
            docUserCollaborationDTO.setId(sysCompanyUserDTO.getId());
            docUserCollaborationDTO.setUsername(sysCompanyUserDTO.getUserName());
            docUserCollaborationDTO.setImgUrl(sysCompanyUserDTO.getImageUrl());
            docUserCollaborationDTO.setPhone(sysCompanyUserDTO.getMobile());

            if (docFile.getCreateUserId() == sysCompanyUserDTO.getId()) {
                docUserCollaborationDTO.setState(1); // 拥有者
            } else if (companyUserIdList.contains(sysCompanyUserDTO.getId())) {
                docUserCollaborationDTO.setState(2); // 协作者
            } else {
                docUserCollaborationDTO.setState(0);
            }

            return docUserCollaborationDTO;

        }).collect(Collectors.toList());

        return docUserCollaborationDTOS;
    }

    /**
     * 接口名称：分页查询文件列表
     * Tag ：文档服务
     * 接口路径：GET/document/pagingFile
     */
    @Override
    public PageResult<DocFileDto> pagingFile(Integer page, Integer pageSize, String keyword) {
        //构建查询条件
        LambdaQueryWrapper<DocFile> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DocFile::getCompanyId,CurrentUserHolder.get().getCompanyId());

        if (!StringUtils.isEmpty(keyword)){
            wrapper.like(DocFile::getName,keyword);
        }

        IPage<DocFile> ipage = new Page<>(page,pageSize);
        ipage = fileMapper.selectPage(ipage,wrapper);

        //获取当前页数据
        List<DocFile> docFileList = ipage.getRecords();

        List<DocFileDto> docFileDtoList = docFileList.stream().map(docFile -> {
            //查询作者姓名,调用系统微服务
            SysCompanyUserDTO companyUserDTO = companyUserFeign.queryCompanyUserById(docFile.getCreateUserId()).getData();

            //查询协作者
            LambdaQueryWrapper<DocCollaborations> collWrapper = new LambdaQueryWrapper<>();
            collWrapper.eq(DocCollaborations::getFileId,docFile.getId());
            List<DocCollaborations> collaborationsList = collaborationsMapper.selectList(collWrapper);

            List<SysCompanyUserDTO> companyUserDTOList = new ArrayList<>();
            for (DocCollaborations docCollaborations : collaborationsList) {
                SysCompanyUserDTO sysCompanyUserDTO = companyUserFeign.queryCompanyUserById(docCollaborations.getCollaborationId()).getData();;
                sysCompanyUserDTO.setWTF(sysCompanyUserDTO.getUserName());
                companyUserDTOList.add(sysCompanyUserDTO);
            }

            DocFileDto docFileDto = new DocFileDto();
            docFileDto.setId(docFile.getId());
            docFileDto.setFolderId(docFile.getFolderId());
            docFileDto.setName(docFile.getName());

            docFileDto.setFileSize(docFile.getFileSize());
            docFileDto.setFilePath(docFile.getFilePath());
            docFileDto.setStatus(docFile.getStatus());
            docFileDto.setCompanyId(CurrentUserHolder.get().getCompanyId());
            docFileDto.setCreateTime(new Date());
            docFileDto.setUpdateTime(new Date());
            docFileDto.setCreator(companyUserDTO);
            docFileDto.setCollaborations(companyUserDTOList);


            return docFileDto;
        }).collect(Collectors.toList());

        return new PageResult<>(ipage.getTotal(),ipage.getPages(),docFileDtoList);
    }

    /**
     * 接口名称：封禁/解封文件
     * Tag ：文档服务
     * 接口路径：PUT/document/{fileId}/{status}
     */
    @Override
    public void updateStatus(Long fileId, Integer status) {
        //参数校验
        if (StringUtils.isEmpty(fileId) || status == null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        DocFile docFile = new DocFile();
        docFile.setId(fileId);
        if (status == 0){
            docFile.setStatus((short) 0);
        }else {
            docFile.setStatus((short) 1);
        }
        fileMapper.updateById(docFile);

        //根据文档id查询文档信息
        DocFileDto fileDto = fileService.getFileByFileId(fileId);
        //编辑历史

        DocFileHistoryDto docFileHistoryDto = new DocFileHistoryDto();
        docFileHistoryDto.setFileId(fileId);
        docFileHistoryDto.setFileName(fileDto.getName());
        docFileHistoryDto.setOperateUserId(CurrentUserHolder.get().getCompanyUserId());
        docFileHistoryDto.setOperateTime(new Date());
        docFileHistoryDto.setIsCreate((short)0);
        docFileHistoryDto.setContent(fileDto.getContent());

        historyMapper.insert(BeanHelper.copyProperties(docFileHistoryDto, DocFileHistory.class));
    }

    @Override
    public List<DocFileHistoryDto> findFileHistory(Long fileId) {
        if (fileId==null){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }
        LambdaQueryWrapper<DocFileHistory> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(DocFileHistory::getFileId,fileId);
        List<DocFileHistory> docFileHistories = historyMapper.selectList(wrapper);
        if (!CollectionUtils.isEmpty(docFileHistories)){
            List<DocFileHistoryDto> docFileHistoryDtos = BeanHelper.copyWithCollection(docFileHistories, DocFileHistoryDto.class);
            List<DocFileHistoryDto> collect = docFileHistoryDtos.stream().map(docFileHistoryDto -> {
                SysCompanyUserDTO data =
                        companyUserFeign.queryCompanyUserById(docFileHistoryDto.getOperateUserId()).getData();
                docFileHistoryDto.setUserName(data.getUserName());
                return docFileHistoryDto;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

}
